import { get, post } from '@/utils/request'
import axios from 'axios'
import { getToken } from '../utils/auth'

// 模型列表接口返回的数据类型
export interface ModelItem {
  id: number
  modelName: string
  modelIcon: string
  modelDesc: string
  modelType: number
  modelTypeName: string
  createTime: number
  updateTime: number
}

// 助手列表接口返回的数据类型
export interface AssistantItem {
  id: number
  assistantName: string
  assistantIcon: string
  assistantPrompt: string
  likeCount: number
  createTime: number
  updateTime: number
}

// 分页参数接口
export interface PageParams {
  page: number
  limit: number
  order?: 'ASC' | 'DESC'
  field?: string
}

// 会话查询参数接口
export interface ConversationQueryParams {
  keyword?: string
  page?: PageParams
}

// 会话数据接口
export interface ConversationItem {
  id: number
  type: number
  typeName: string
  title: string
  totalToken: number
  createTime: number
  updateTime: number
}

// 分页响应接口
export interface PageResponse<T> {
  pageNo: number
  pageSize: number
  totalCount: number
  totalPage: number
  data: T[]
}

// 会话消息接口
export interface ConversationMessage {
  id: number
  modelId: number
  modelName: string
  type: number
  messageContent: string
  createTime: number
  updateTime: number
}

// 聊天请求参数接口
export interface ChatRequest {
  conversationId?: number
  modelId?: number
  message: string
  modelName?: string
  assistantId?: number
  customSystemPrompt?: string
  fileList?: number[]
}

// 绘图接口参数
export interface DrawRequest {
  prompt: string
  ratio: string
  base64Array?: string[]
}

// MJ任务查询请求参数
export interface MjQueryRequest {
  id: number
}

// MJ任务结果接口
export interface MjTaskResult {
  taskId?: number
  action?: string
  buttons?: Array<{
    label: string
    style: number
    type: number
  }>
  customId?: string
  emoji?: string
  label?: string
  style?: number
  type?: number
  description?: string
  failReason?: string
  finishTime?: number
  id?: string
  imageUrl?: string
  progress?: string
  prompt?: string
  promptEn?: string
  startTime?: number
  state?: string
  status?: string
  submitTime?: number
}

// 新增绘图任务结果接口
export interface DrawTaskResult {
  id?: number
  prompt?: string
  ratio?: string
  imgNum?: number
  imgList?: string[]
  progress?: string
  status?: number
  createTime?: number
  updateTime?: number
  failReason?: string
}

// 模型分类接口返回的数据类型
export interface ModelCategoryItem {
  id: number
  modelCategoryIcon: string
  modelCategoryName: string
  modelCategoryDesc: string
}

// 新增接口返回类型
export interface ConsumeDataItem {
  chatConsumeCount: number
  DrawConsumeCount: number
  VideoConsumeCount: number
  dataDate: string
}

// 获取所有模型列表，可选关键字搜索
export const getAllModelList = (keyword?: string) => {
  const params = keyword ? { keyword } : {}
  return get<ModelItem[]>('/ai-api/ai/model/list', params)
}

// 获取所有模型分类
export const getModelCategoryList = () => {
  return post<ModelCategoryItem[]>('/ai-api/ai/model/category/list')
}

// 获取分类下的模型列表
export const getCategoryModelList = (modelCategoryId: number) => {
  return post<ModelItem[]>('/ai-api/ai/model/category/model/list', { modelCategoryId })
}

// 保持原来的方法名称兼容性
export const getModelList = getAllModelList

// 获取助手列表
export const getAssistantList = (keyword?: string) => {
  const params = keyword ? { keyword } : { keyword: '' }
  return get<AssistantItem[]>('/ai-api/ai/assistant/list', params)
}

// 分页查询会话
export const getConversationList = (params: ConversationQueryParams) => {
  return post<PageResponse<ConversationItem>>('/ai-api/ai/conversation/page', params)
}

// 获取会话消息列表
export const getConversationMessages = (conversationId: number) => {
  return get<ConversationMessage[]>(
    `/ai-api/ai/conversation/message?conversationId=${conversationId}`,
  )
}

// 发送聊天消息
export const sendChatMessage = (params: ChatRequest, onMessage: (data: string) => void) => {
  const controller = new AbortController()
  const signal = controller.signal
  const token = getToken()
  const promise = axios.post('/ai-api/ai/chat', params, {
    responseType: 'stream',
    headers: {
      Accept: 'application/json, text/plain, */*',
      Authorization: token,
    },
    signal,
    onDownloadProgress: (progressEvent) => {
      const responseText = progressEvent.event.target?.responseText
      if (!responseText) return

      const lines = responseText.split('\n')
      for (const line of lines) {
        if (line.startsWith('data:')) {
          try {
            const jsonStr = line.slice(5).trim()
            if (!jsonStr) continue

            const data = JSON.parse(jsonStr)
            if (data.code === 200 && data.status && data.data !== undefined) {
              onMessage(data.data)
            }
          } catch (e) {
            console.error('解析SSE数据失败:', e)
          }
        }
      }
    },
  })

  return {
    promise,
    cancel: () => controller.abort(),
  }
}

export const createConversation = (params: { title?: string; type?: number }) => {
  return post('/ai-api/ai/conversation/create', params)
}

// 删除会话
export const deleteConversation = (id: number) => {
  return post('/ai-api/ai/conversation/del', { id })
}

// 重命名会话
export const renameConversation = (params: { id: number; title: string }) => {
  return post('/ai-api/ai/conversation/edit', params)
}

// 提交MJ绘图任务
export const submitMjDrawTask = (params: DrawRequest) => {
  return post<MjTaskResult>('/ai-api/ai/draw/mj/submit', params)
}

// 查询MJ任务进度
export const queryMjTaskProgress = (id: number) => {
  return post<DrawTaskResult>('/ai-api/ai/draw/mj/query', { id })
}

// 提交DALL-E绘图任务
export const submitDallEDrawTask = (params: DrawRequest) => {
  return post('/ai-api/ai/draw/dalle/submit', params)
}

// 获取绘图任务结果
export const getDrawTaskResult = (taskId: string) => {
  return get(`/ai-api/ai/draw/result?taskId=${taskId}`)
}

// 获取绘图历史记录
export const getDrawHistory = (params: PageParams) => {
  return post('/ai-api/ai/draw/history', params)
}

// 绘图任务分页查询接口
export const getDrawTaskPage = (params: {
  page?: {
    page: number
    limit: number
    order?: 'ASC' | 'DESC'
    field?: string
  }
}) => {
  return post<{
    code: number
    status: boolean
    message: string
    data: {
      pageNo: number
      pageSize: number
      totalCount: number
      totalPage: number
      data: DrawTaskResult[]
    }
  }>('/ai-api/ai/draw/mj/page', params)
}

// 删除绘图任务
export const deleteDrawTask = (id: number) => {
  return post('/ai-api/ai/draw/del', { id })
}

// 执行MJ命令
export const executeMjCommand = (params: { id: number; customId: string }) => {
  return post<MjTaskResult>('/ai-api/ai/draw/mj/command', params)
}

// 获取用户消费数据
export const getUserConsumeData = async (dayCount?: number) => {
  try {
    console.log('调用getUserConsumeData, dayCount:', dayCount);
    const params = dayCount ? { dayCount } : { dayCount: 30 };
    console.log('请求参数:', params);
    const result = await post<ConsumeDataItem[]>('/ai-api/ai/bi/getUserConsumeData', params);
    console.log('getUserConsumeData请求成功, 结果:', result);
    return result;
  } catch (error) {
    console.error('getUserConsumeData请求失败:', error);
    throw error;
  }
}
